<template>
  <div v-loading.fullscreen.lock="viewLoading">
    <CrudView
      :form-data="formData"
      :form-items="formItems"
      :btn-items="btnItems"
      :page-colums="pageColums"
      :page-data="{pageInfo, list}"
      :selection-change-handler="selectionChangeHandler"
    />
    <!-- 开课信息编辑/新增模态框  -->
    <el-dialog
      :title="modalTitle"
      :center="true"
      :visible.sync="showModal"
      :before-close="closeModal"
    >
      <el-form :model="modalData" label-width="90px" :disabled="modalModel === 'Look'" label-position="top">
        <el-tabs v-model="activename">
          <el-tab-pane label="基本信息" name="first">
            <div style="max-height: 400px;overflow: auto">
              <el-form-item label="所属课程">
                <el-select v-model="modalData.courseId">
                  <el-option v-for="item in dropDownData.course" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="教学班名称">
                <el-input v-model="modalData.teachClassName" type="text" />
              </el-form-item>
              <el-form-item label="开设学年">
                <el-date-picker v-model="modalData.teachYear" type="year" value-format="yyyy" format="yyyy" />
              </el-form-item>
              <el-form-item label="开设学期">
                <el-select v-model="modalData.teachTerm">
                  <el-option label="第一学期" :value="1" />
                  <el-option label="第二学期" :value="2" />
                  <el-option label="第三学期" :value="3" />
                </el-select>
              </el-form-item>
              <el-form-item label="授课教师姓名">
                <el-autocomplete
                  v-model="modalData.teacherName"
                  placeholder="请输入教师姓名..."
                  value-key="label"
                  :trigger-on-focus="false"
                  :fetch-suggestions="queryTeachers"
                  @select="selectTeacher"
                />
              </el-form-item>
              <el-form-item label="授课教师工号">
                <el-input v-model="modalData.teacherNo" type="text" disabled />
              </el-form-item>
              <el-form-item label="预计上课人数">
                <el-input v-model="modalData.expectedPeopleNum" type="number" />
              </el-form-item>

              <el-form-item v-if="modalModel !== 'Look'">
                <el-button @click="modalCancelHandler">取消</el-button>
                <el-button type="primary" @click="modalSubmitHandler">提交</el-button>
              </el-form-item>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import CrudView from '@/components/CrudView'
import { getCourseDropDown } from '@/api/ms/dropdown'
import { getTeacherDropDownByName } from '@/api/ms/dropdown'
import { getPage, getById, update, create, deleteByIds } from '@/api/ms/course/course/courseSchedule'
// vue对象钩子
let vueHook = null

function getDefaultModalData() {
  return { // 默认的开课基本信息信息编辑/新增modal框数据
    id: null,
    courseId: null,
    teachClassName: '',
    teachYear: null,
    teachTerm: null,
    teacherNo: null,
    teacherName: '',
    expectedPeopleNum: null
  }
}

export default {
  name: 'CourseScheduleSchedule',
  components: { CrudView },
  data() {
    return {
      viewLoading: false,
      formData: {
        courseId: null,
        teachClassName: '',
        teachYear: null,
        teachTerm: null,
        teacherName: ''
      },
      dropDownData: {
        // 课程下拉数据
        course: []
      },
      formItems: [
        { order: 1, label: '所属课程', type: 'Select', paramName: 'courseId', options: [] },
        { order: 2, label: '教学班名称', type: 'Input', paramName: 'teachClassName' },
        { order: 3, label: '开设学年', type: 'Year', paramName: 'teachYear' },
        { order: 4, label: '开设学期', type: 'Select', paramName: 'teachTerm', options: [
          { label: '第一学期', value: 1 },
          { label: '第二学期', value: 2 },
          { label: '第三学期', value: 3 }
        ] },
        { order: 4, label: '教师姓名', type: 'Input', paramName: 'teacherName' },
        { order: 5, type: 'Button', btnName: '查询', clickHandler: () => {
          vueHook.ignoreRefresh = true
          vueHook.pageInfo.pageNum = 1
          vueHook.refreshPageList()
        }
        }
      ],
      btnItems: [
        { order: 1, name: '查看', type: 'primary', clickHandler: () => vueHook.openModal('Look') },
        { order: 2, name: '编辑', type: 'warning', clickHandler: () => vueHook.openModal('Edit') },
        { order: 3, name: '添加', type: 'success', clickHandler: () => vueHook.openModal('Create') },
        { order: 4, name: '删除', type: 'danger', clickHandler: () => vueHook.batchDeleteCourseSchedule() }
      ],
      pageColums: [
        { label: '教学班名称', propName: 'teachClassName' },
        { label: '所属课程名称', propName: 'courseName' },
        { label: '开课学年', propName: 'teachYear' },
        { label: '开课学期', propName: 'teachTerm' },
        { label: '教学时段', propName: 'teachTimeName' },
        { label: '上课教室', propName: 'classroomName' },
        { label: '授课教师', propName: 'teacherName' },
        { label: '预计上课人数', propName: 'expectedPeopleNum' }
      ],
      pageInfo: {
        pageNum: 1, // 当前页
        pageSize: 10, // 每页行数
        total: 1000 // 列表总行数
      },
      selectionChangeHandler: (srows) => { // 记录选择改变handler
        vueHook.ids = srows.map(i => i.id)
      },
      list: [], // 数据列表
      ignoreRefresh: false,
      ids: [], // 选中的id列表
      showModal: false, // modal框显示标识
      modalTitle: '', // modal标题
      modalModel: 'Look', // modal状态 ，分别为 Look、Edit、Create
      activename: 'first',
      modalData: {} // 开课基本信息信息编辑/新增modal框数据
    }
  },
  computed: {
    // 分页参数组装
    pageParam() {
      const formData = this.formData
      const pageInfo = this.pageInfo
      return { ...formData, pageInfo }
    }
  },
  watch: {
    pageInfo: {
      handler(val) {
        if (this.ignoreRefresh) {
          // 需要忽略本次change
          this.ignoreRefresh = false
          return
        }
        // 向后台请求新的表格数据
        this.refreshPageList()
      },
      deep: true
    }
  },
  mounted() {
    // 暴露vue对象
    vueHook = this
    // 请求下拉框数据
    this.refreshDropDown()
    // 向后台请求新的表格数据
    this.refreshPageList()
  },
  methods: {
    // “授课教师姓名”表单域候选输入处理
    queryTeachers(qstr, callback) {
      if (!qstr || qstr.length === 0) {
        return
      }
      // 从后台查询匹配的教师信息列表
      getTeacherDropDownByName(qstr).then(({ data }) => {
        this.dropDownData.teacher = data
        callback(data)
      })
    },
    // “授课教师姓名”表单域候选选择处理
    selectTeacher(item) {
      this.modalData.teacherNo = item.value
    },
    // 刷新表单下拉框数据
    refreshDropDown() {
      // 获取课程下拉数据
      getCourseDropDown().then(({ data }) => {
        this.dropDownData.course = data
        this.formItems[0].options = data
      })
    },
    // 刷新开课基本信息列表数据
    refreshPageList() {
      getPage(this.pageParam).then(({ list, pageInfo }) => {
        this.ignoreRefresh = true
        this.list = list
        this.pageInfo = pageInfo
      })
    },
    // 打开开课信息编辑/新增modal
    openModal(model) {
      // 如果是Create操作，直接打开modal
      if (model === 'Create') {
        // 打开modal
        this.modalTitle = '开课信息创建'
        this.modalModel = model
        this.showModal = true
        return
      }

      // 获取选中的开课id列表
      const ids = this.ids
      if (!ids || ids.length === 0) {
        this.$message.error('请选择一条记录')
        return
      }
      if (ids.length > 1) {
        this.$message.error('只能选择一条记录')
        return
      }
      // 获取开课详细信息 ，成功后打开modal
      getById(ids[0]).then(({ data }) => {
        this.modalData = data
        // data后置处理
        this.postHandleModalData()
        // 打开modal
        this.modalModel = model
        this.modalTitle = model === 'Edit' ? '开课信息编辑' : '开课信息详情'
        this.showModal = true
      })
    },
    // 关闭开课信息编辑/新增modal
    closeModal() {
      this.showModal = false
      // 重置modal数据
      this.activename = 'first'
      this.modalData = getDefaultModalData()
    },
    // 点击modal取消按钮
    modalCancelHandler() {
      this.closeModal()
    },
    // 点击modal提交按钮
    modalSubmitHandler() {
      if (this.modalModel === 'Edit') {
        this.updateCourseScheduleInfo()
      } else if (this.modalModel === 'Create') { this.createCourseScheduleInfo() }
    },
    // 创建开课信息
    createCourseScheduleInfo() {
      create(this.modalData).then((res) => {
        this.$message.success(res.message)
        // 刷新数据
        this.refreshPageList()
        // 关闭modal
        this.closeModal()
      }).catch(err => {
        console.log(err)
        // 关闭modal
        this.closeModal()
      })
    },
    // 修改开课信息
    updateCourseScheduleInfo() {
      update(this.modalData).then((res) => {
        this.$message.success(res.message)
        // 刷新数据
        this.refreshPageList()
        // 关闭modal
        this.closeModal()
      }).catch(err => {
        console.log(err)
        // 关闭modal
        this.closeModal()
      })
    },
    // 批量删除开课信息(逻辑删除)
    batchDeleteCourseSchedule() {
      if (this.ids === null || this.ids.length < 1) {
        this.$message.error('请至少选择一条记录')
        return
      }
      this.$confirm('请确认是否删除？').then(() => {
        deleteByIds(this.ids).then(res => {
          this.$message.success(res.message)
          // 刷新数据
          this.refreshPageList()
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {
        this.$message.info('删除已取消')
      })
    },
    // 处理modalData，将teachYear从Number转为String
    postHandleModalData() {
      const year = this.modalData.teachYear
      if (year) {
        this.modalData.teachYear = year.toString()
      }
    }
  }
}
</script>

<style>

</style>

